﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Linq.Expressions;
namespace DAO.Bussiness
{
    public class Repository<T> : IRepository<T> where T : class
    {
        private barCafeContext ctx;

        public Repository()
        {
            ctx = new barCafeContext();
        }


        public void Add(T entity)
        {
            ctx.Set<T>().Add(entity);
        }

        public void Add(List<T> entities)
        {
            foreach (T entity in entities)
            {
                ctx.Set<T>().Add(entity);
            }
        }

        public void Delete(T entity)
        {
            ctx.Set<T>().Remove(entity);
        }

        public void Update(T entity)
        {
            ctx.Entry(entity).State = System.Data.EntityState.Modified;
        }

        public IEnumerable<T> All()
        {
            return ctx.Set<T>();
        }

        public IEnumerable<T> GetBy(Expression<Func<T, bool>> predicate)
        {
            return ctx.Set<T>().Where(predicate);
        }

        public void Save()
        {
            ctx.SaveChanges();
        }


        public void LoadGrid(ref GridView grid, Expression<Func<T, bool>> predicate = null)
        {
            if (predicate != null)
            {
                grid.DataSource = GetBy(predicate).ToList();
            }
            else
            {
                grid.DataSource = All().ToList();
            }
            grid.DataBind();
        }

      
    }
}
